package com.msda.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msda.pojo.entity.Token;
import com.msda.exception.TokenException;
import com.msda.mapper.TokenMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;

import static com.msda.constant.MessageConstant.TOKEN_NOT_EXPIRE;

public class LoginInterceptor implements HandlerInterceptor {

    private TokenMapper tokenMapper;

    public LoginInterceptor(TokenMapper tokenMapper){
        this.tokenMapper = tokenMapper;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("authorization");
        if(token == null || token.isBlank()){
            throw new TokenException("token为空！");
        }
        QueryWrapper<Token> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token",token);
        Token token1 = tokenMapper.selectOne(queryWrapper);

        if(token1 == null){
            throw new TokenException(TOKEN_NOT_EXPIRE);
        }
        LocalDateTime localDateTime = token1.getExpireTime().plusDays(1);
        if(localDateTime.isBefore(LocalDateTime.now())){
            tokenMapper.delete(queryWrapper);
            throw new TokenException(TOKEN_NOT_EXPIRE);
        }
        return true;
    }
}
